<?php

App::uses('AppController', 'Controller');

/**
 * Categories Controller
 *
 * @property Category $Category
 * @property PaginatorComponent $Paginator
 */
class CategoriesController extends AppController
{

    /**
     * Components
     *
     * @var array
     */
    public $components = array('Paginator', 'Session');

    //var $userid = CakeSession::read('userId');

    /**
     * index method
     *
     * @return void
     */

    public function index()
    {
        $this->Category->recursive = 0;
        $user = $this->Auth->user();
        //debug($this->Auth->user());
        $this->paginate = array('limit' => '10',
            'order' => 'Category.id',
            'conditions' => array(
                'OR' => array(
                    array('Category.user_id' => $user['id']),
                    array('Category.user_id' => 20)
                ),
            ),
            'ORDER' => array('Category.id' => 'DESC')
        );
        // debug($this->Paginator->paginate());
        $this->set('categories', $this->Paginator->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null)
    {
        if (!$this->Category->exists($id))
        {
            throw new NotFoundException(__('Invalid category'));
        }
        $options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
        $this->set('category', $this->Category->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add()
    {
        if ($this->request->is('post'))
        {
            $this->Category->create();
            $data = $this->request->data;
            if ($this->Category->save($data))
            {

                $this->Session->setFlash(__('The category has been saved.'), 'alert-success');
                return $this->redirect(array('action' => 'index'));
            } else
            {
                $this->Session->setFlash(__('The category could not be saved. Please, try again.'), 'alert-danger');
            }
        }

        $userId = $this->Auth->user('id');
        $condition = array('fields' => array('User.id', 'User.username'), 'conditions' => array('User.id' => $userId));
        $users = $this->Category->User->find('all', $condition);

        $sql1 = "SELECT `Pcat`.`id` , `Pcat`.`name`  "
                . "FROM `tb_categories` AS `Pcat`  "
                . "WHERE `Pcat`.`parent_id` =0 "
                . "AND `Pcat`.`user_id`={$userId} "
                . "OR `Pcat`.`user_id`= 20 AND `Pcat`.`type`=1";
        //Get parent
        $condition2 = array('fields' => array('Category.id', 'Category.name'), 'conditions' => array('Category.parent_id' => '0'));

        $parentCategories = $this->Category->query($sql1);
        //debug($parentCategories);


        $this->set(compact('users', 'parentCategories'));
    }

    /**
     * get parent category method
     * @return parent category
     */

    public function jQueryGetPcat()
    {
        $this->autoRender = false;
        if ($this->request->is('ajax'))
        {

            //get type
            $type = $this->request->data('value');
            //value = 1: Sept; 2:Earn
            $userId = $this->Auth->user('id');
            $sql = "SELECT cat.id, name
                    FROM tb_categories AS cat
                    WHERE type = {$type}
                    AND cat.user_id = 20
                    OR cat.user_id = {$userId}
                    AND cat.parent_id = 0
                    ";
            $this->loadModel('User');
            $datas = $this->Category->query($sql);
            $parent = array();
            $parent['0'] = '-- No Parent --';
            foreach ($datas as $item)
            {
                $parent[$item['cat']['id']] = $item['cat']['name'];
            }
            echo(json_encode($parent));
        }
    }

    /**
     * edit method
     * @param string id
     * @return void
     */

    public function edit($id = null)
    {
        if (!$this->Category->exists($id))
        {
            throw new NotFoundException(__('Invalid category'));
        }
        if ($this->request->is(array('post', 'put')))
        {
            $data = $this->request->data;
            $this->Category->id = $id;

            if ($this->Category->save($data))
            {
                $this->Session->setFlash(__('The category has been saved.'), 'alert-success');
                return $this->redirect(array('action' => 'index'));
            } else
            {
                $this->Session->setFlash(__('The category could not be saved. Please, try again.'), 'alert-danger');
            }
        } else
        {
            $options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
            $this->request->data = $this->Category->find('first', $options);
        }


        $Category = $this->Category->find('first', array('conditions' => array('Category.id' => $id)));
        $parents = $this->Category->find('all', array('conditions' =>
            array(
                'NOT' => array('Category.parent_id' => '0'),
                'Category.type' => $Category['Category']['type'] + 1,
                'OR' => array('Category.user_id' => 20, 'Category.user_id' => $this->Auth->user('id')
                )
            ),
            'fields' => array('Category.id', 'Category.name'),
            'recursive' => 0,
                )
        );
        $parentCategory = $this->Category->find('list', array('conditions' => array('Category.type' => $Category['Category']['type'] + 1, 'Category.parent_id' => 0)));
        $this->set(compact('users', 'Category', 'parentCategory'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function delete($id = null)
    {
        $this->Category->id = $id;
        if (!$this->Category->exists())
        {
            throw new NotFoundException(__('Invalid category'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Category->delete())
        {
            $this->Session->setFlash(__('The category has been deleted.'), 'alert-success');
        } else
        {
            $this->Session->setFlash(__('The category could not be deleted. Please, try again.'), 'alert-danger');
        }
        return $this->redirect(array('action' => 'index'));
    }

    public function isAuthorized($user)
    {
        if (in_array($this->action, array('edit', 'delete')))
        {
            if ($user['id'] != $this->Auth->user('id'))
            {
                return false;
            }
        }
        return true;
    }

}
